<?php
		

	function read_header($ch, $string) {
		global $headers;
//		echo $string;
	    $length = strlen($string);
	    if (false===strpos($string,"Transfer-Encoding"))
	   		$headers[]=$string;	
	    return $length;
	}
	
/* SPLIT PROXY FROM URL TO QUERY. QUERY: ALL INSIDE THE 'S' PARAMETER */
		
        $url = $_GET['url'];		
		$headers=array();

/* SET INTERNAL PROXY */
        $proxy = "";
        $proxy = "http://wwwcache.ebi.ac.uk:3128/";
        //$proxy = "http://wwwcache.sanger.ac.uk:3128/";


/* CURL CONFIGURARTION */
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(strlen($proxy) != 0){
                curl_setopt($ch, CURLOPT_PROXY, "$proxy");
        }
        /* Don't return HTTP headers. Do return the contents of the call */
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HEADERFUNCTION,"read_header");
		
		$expectedXMLAnswer=true;		
		
/* DISPLAY DATA FROM THE ORIGINAL QUERY */
        $data = curl_exec($ch);
        curl_close($ch);
        
        //OUTSIDE EBI
        $flag = strpos($url, ".pdb");
        $outside = "true";
        $CACHE_PATH = "../server/pdb/";
        
        //INSIDE EBI
        //$flag = strpos($url, "pdbe");
        
        if ($flag) {
            header("Content-Type: text/plain");
            if ($outside) {
            	$lastSlash = strrpos($url, "/");
            	//echo $lastSlash . "\n";
            	$pdbFileName = substr($url, $lastSlash+1);
            	//echo $pdbFileName . "\n";
            	$pdbFileName = $CACHE_PATH . $pdbFileName;
            	//echo $pdbFileName . "\n";
            	$pdbFileHandle = fopen($pdbFileName, 'w') or die("$pdbFileName cannot be created/opened");
            	fwrite($pdbFileHandle, $data);            	
            	fclose($pdbFileHandle);            	
            }
        } else {
            header("Content-Type: text/xml");
        }
        echo $data;
?>
